import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// 轮播图数据接口
interface BannerData {
  id?: number;
  title: string;
  image: string;
}

/**
 * 采集轮播图数据
 */
export async function crawlBanners(): Promise<BannerData[]> {
  try {
    // 发送请求获取腾讯视频首页轮播图数据
    const headers = new Headers({
      "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
      "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
      "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
      "cache-control": "max-age=0",
      "upgrade-insecure-requests": "1"
    });

    const requestOptions = {
      method: 'GET',
      headers: headers,
      redirect: 'follow' as RequestRedirect
    };

    const response = await fetch("https://v.qq.com/channel/choice", requestOptions);

    const html = await response.text();

    // 提取初始状态数据
	// __vikor__context__._piniaState.channelPageData.channelsModulesMap["100101"].cardListData[0].focusList
    const stateMatch = html.match(/<script>window\.__vikor__context__\s*=\s*({.*?})<\/script>/);
    if (!stateMatch) {
      throw new Error('无法提取页面初始状态数据');
    }
    // 解析JSON数据
    const initialState = JSON.parse(stateMatch[1]);
    const data = initialState._piniaState.channelPageData.channelsModulesMap["100101"].cardListData[0].focusList;

    if (data.length === 0) {
      return []
    }

    // 查询数据库中已标记为轮播图的视频
    const carouselVideos = await prisma.video.findMany({
      where: {
        isCarousel: true
      },
      select: {
        id: true,
        vodName: true
      }
    });

    // 提取轮播图数据
    const banners: BannerData[] = [];

    for (const item of data) {
      if (item.title && item.coverPic) {
        banners.push({
          title: item.title,
          image: item.coverPic || '/images/placeholder.jpg'
        });
      }
    }
    const update_banners: BannerData[] = []
    // 使用Promise.all处理异步操作
    await Promise.all(banners.map(async (banner) => {
      // 处理标题匹配问题
      // 标题格式转换，解决数据库匹配问题，例如：
      // - "哈哈哈哈哈 第5季" 需匹配 "哈哈哈哈哈第五季"
      // - "开始推理吧3" 需匹配 "开始推理吧第三季"
      // - "奔跑吧9" 需匹配 "奔跑吧第九季"
      
      // 数字到中文数字的映射
      const numMap: Record<string, string> = {
        '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', 
        '6': '六', '7': '七', '8': '八', '9': '九', '10': '十'
      };
      
      // 生成多种可能的标题格式用于匹配
      const possibleTitles = [
        banner.title, // 原始标题
        banner.title.replace(/\s+/g, ''), // 移除空格
      ];
      
      // 处理 "剧名+数字" 格式 (如"奔跑吧9"转为"奔跑吧第九季")
      const nameWithNumberMatch = banner.title.match(/^(\D+)(\d+)$/);
      if (nameWithNumberMatch) {
        const name = nameWithNumberMatch[1];
        const num = nameWithNumberMatch[2];
        const chineseNum = numMap[num] || num;
        possibleTitles.push(`${name}第${chineseNum}季`);
        possibleTitles.push(`${name} 第${chineseNum}季`);
        possibleTitles.push(`${name}第${num}季`);
      }
      
      // 处理 "剧名 第N季" 格式
      const spaceSeasonMatch = banner.title.match(/^(.+)\s+第(\d+)季$/);
      if (spaceSeasonMatch) {
        const name = spaceSeasonMatch[1];
        const num = spaceSeasonMatch[2];
        const chineseNum = numMap[num] || num;
        possibleTitles.push(`${name}第${chineseNum}季`);
        possibleTitles.push(`${name}第${num}季`);
      }
      
      // 处理 "第N季" 转换为中文数字
      const seasonMatch = banner.title.match(/第(\d+)季/);
      if (seasonMatch) {
        const num = seasonMatch[1];
        const chineseNum = numMap[num] || num;
        possibleTitles.push(
          banner.title.replace(/第\d+季/, `第${chineseNum}季`)
        );
      }
      
      // 去重
      const uniqueTitles = [...new Set(possibleTitles)];
      
      // 构建查询条件
      const exactMatchConditions = uniqueTitles.flatMap(title => [
        { vodName: title },
        { vodSub: title }
      ]);
      
      // 先尝试精确匹配
      let video = await prisma.video.findFirst({
        where: {
          OR: exactMatchConditions
        },
        orderBy: {
          vodTime: 'desc'  // 按时间降序排序，最新的视频优先
        }
      });

      // 如果精确匹配没有结果，再尝试模糊匹配
      if (!video) {
        // 只使用原始标题和无空格标题进行模糊匹配，避免过多的查询
        const fuzzyMatchTitles = uniqueTitles.slice(0, 2);
        const fuzzyMatchConditions = fuzzyMatchTitles.flatMap(title => [
          { vodName: { contains: title } },
          { vodSub: { contains: title } }
        ]);
        
        video = await prisma.video.findFirst({
          where: {
            OR: fuzzyMatchConditions
          },
          orderBy: {
            vodTime: 'desc'
          }
        });
      }
      if (video) {
        banner.id = video.id
        // 更新视频的轮播图信息
        await prisma.video.update({
          where: { id: video.id },
          data: {
            carouselPic: banner.image || '/images/placeholder.jpg',
            isCarousel: true
          }
        });
        update_banners.push(banner)
      }
    }));
    
    if (update_banners.length !== banners.length) {
      // 计算未更新的轮播图数据
      const notUpdatedBanners = banners.filter(banner =>
        !update_banners.some(updatedBanner => updatedBanner.id === banner.id)
      );
      // 输出未更新的轮播图信息
      if (notUpdatedBanners.length > 0) {
        console.log(`有 ${notUpdatedBanners.length} 个轮播图未能更新:`);
        notUpdatedBanners.forEach(banner => {
          console.log(`  - 标题: ${banner.title}`);
        });
      }
    }

    // 移除不再是轮播图的视频标记
    // 比较carouselVideos和update_banners的id，找出不再是轮播图的视频
    const carouselVideoIds = carouselVideos.map(video => video.id);
    const updatedBannerIds = update_banners.map(banner => banner.id);
    
    // 找出在carouselVideos中但不在update_banners中的视频ID
    const videosToRemoveCarousel = carouselVideoIds.filter(
      id => !updatedBannerIds.includes(id)
    );
    
    if (videosToRemoveCarousel.length > 0) {
      // 更新这些视频，移除轮播图标记
      await prisma.video.updateMany({
        where: {
          id: {
            in: videosToRemoveCarousel
          }
        },
        data: {
          isCarousel: false
        }
      });
      
      console.log(`已移除 ${videosToRemoveCarousel.length} 个不再是轮播图的视频标记`);
    }
    
    return update_banners;
  } catch (error) {
    console.error('采集轮播图数据失败:', error);
    throw error;
  } finally {
    await prisma.$disconnect();
  }
}

/**
 * 删除所有轮播图数据
 */
export async function deleteAllBanners(): Promise<number> {
  return 0;
} 